<template>
	<view class="content">
		<!-- 404页面 -->
		<view class="noData" v-if="netWorkType == 'none'">
			<noData @handle="refresh"></noData>
		</view>
		<view v-if="netWorkType != 'none'">
			<tui-skeleton v-if="skeletonShow" backgroundColor="#fafafa" borderRadius="10rpx"></tui-skeleton>
			<view class="container tui-skeleton">

				<!-- 头部	 开始-->
				<view class="head-box marginleft15 marginright15">

					<view class="flex-box">
						<view class="head-list">
							<view v-if="data.check.status!=undefined"
								class="bg-white padright15 border-radius8 padbottom5"
								style="margin-bottom: 24rpx;padding-left: 26rpx;">

								<view class="time">
									<view class="lf">{{data.check.create_time}}</view>
									<!-- <view class="rg">

									</view> -->
								</view>
								<view class="data-box   ">
									<view class="lf">
										<view class="word">{{product_type==3?data.check.glu:data.check.ua}}</view>
									</view>
									<view class="rg">
										<view v-if="product_type==3">
											<tui-tag v-if="data.check.status==1" size="small" padding="12rpx"
												type="dev-green">正常</tui-tag>
											<tui-tag v-if="data.check.status==2" size="small" padding="12rpx"
												type="dev-red">异常</tui-tag>
											<tui-tag v-if="data.check.status==3" size="small" padding="12rpx"
												type="dev-red" style="color: #FF4141 !important;">异常</tui-tag>

										</view>
										<view v-else>
											<tui-tag v-if="data.check.status==1" size="small" padding="12rpx"
												type="dev-green">正常</tui-tag>
											<tui-tag v-if="data.check.status==2" size="small" padding="12rpx"
												type="dev-red">异常</tui-tag>

											<span v-if="gender==0" class="iconfont gender-girl" @tap="genderPopup()"  >&#xe704</span>
											<span v-else-if="gender==1" class="iconfont gender-man" @tap="genderPopup()" >&#xe705</span>
										</view>
										<view class="word" v-if="product_type==3">
											{{data.check.unit_type_desc?data.check.unit_type_desc:''}}
										</view>
										<view class="word" v-else>
											μmol/L
										</view>
									</view>
								</view>
							</view>
							<view v-else class="bg-white padright15 border-radius8  "
								style="margin-bottom: 24rpx;padding-left: 26rpx;">
								<view class="data-box  padtop10" style="position: relative;top: 44rpx;">
									<view class="lf">
										<view style="color:#6F6F6F;" class="word">- -</view>
									</view>
								</view>
							</view>
						</view>
						<!-- 设备状态按钮 -->
						<view style="margin-top: 60rpx;">
								<tui-tag v-if="!isBindDev" shape="circle" type="green" @tap="toBindDev" >绑定设备</tui-tag>
								<tui-tag v-else-if="isBindDev && connStatus==0" shape="circle" type="theme-gray" @click = "link">去连接</tui-tag>
								<tui-tag v-else-if="isBindDev && connStatus==1" shape="circle" type="theme-gray">连接中...</tui-tag>
								<tui-tag v-else-if="isBindDev && connStatus==2" shape="circle" type="theme-blue">已连接</tui-tag>
							</view>

						</view>

					</view>

				</view>

				<!-- 头部	 结束-->
				<!--测试结果反馈	 开始-->
				<view class="res-box marginleft15 marginright15">
					<view class="flex-box margin-bottom20">
						<view class="item">
							<view class="font16 font-bold margin-bottom5">数据分析</view>

						</view>
						<view class="item" @tap="testResult">

							<view class="iconfont font14  word" style="color: #5B9DFF;">
								&#xe6c1;测试说明
							</view>

						</view>
					</view>
					<view class="flex-box margin-bottom20 bg">
						<view class="res-list">
							<!-- 血糖数据分析 -->
							<view class="border-radius8 pd" v-if="product_type==3">
								<view v-if="data.check.status==1" class="title">
									您今日测试数据正常,请继续保持良好的生活习惯,坚持做测试
								</view>
								<view v-else-if="data.check.status==2" class="title">
									您今日测试数据血糖偏低,请及时到医院检查
								</view>
								<view v-else-if="data.check.status==3" class="title">
									您今日测试数据血糖偏高,请及时到医院检查
								</view>
								<view v-else class="title">
									你暂未检测血糖数据
								</view>
							</view>
							<!-- 尿酸数据分析 -->
							<view class="border-radius8 pd" v-else>
							   {{data.desc?data.desc:'你暂未检测尿酸数据'}}
							</view>
						</view>


					</view>
				</view>
				<!-- 测试结果反馈	 结束-->

				<!--图表	 开始-->
				<view class="week-trend    bg-white padtop15">
					<view class="flex-box padleft15 padright15">
						<text class="font16 font-bold">{{product_type==3?'血糖':'尿酸'}}波动趋势</text>

						<view class="viewMore font12 text-center" @tap="testRecord">
							<view>
								<text class="font14 font-gray2">查看更多</text>
								<text class="iconfont padleft5 font12 font-gray">&#xe62b;</text>
							</view>
						</view>
					</view>

					<view class="echart-view"   >
						<view class="f2_container ">
							<canvas v-show="!canvasImg"  type="2d" class="f2-canvas" canvas-id="f2-canvas"   @touchStart="touchStart" @touchMove="touchMove" @touchEnd="touchEnd" />
							<image v-show="canvasImg" :src="canvasImg" :style="{width:echartWidth+'px',height:echartHeight+'px'}" />
						</view>

					</view>

				</view>
				<!-- 图表		 结束-->
				<!--文章	 开始-->

				<view class="relate-prod-list">
					<view class="flex-box font16 padbottom15 padleft15 padright15 font-bold padtop15"
						style="padding-left: 5px;">

						<!-- <view style="width:4px;height:20px;background-color:#3894FF;"></view> -->
						<view style="padding-left: 15px; margin-left: -5px;">文章推荐</view>

						<view @tap="pageArticleList">
							<text class="font14 font-gray2">查看更多</text>
							<text class="iconfont padleft5 font12 font-gray">&#xe62b;</text>
						</view>
					</view>

					<view class="box bg-white marginleft15 marginright15 pad-all10 p-relative"
						v-for="(item,index) in data.article">
						<view class="flex-start-box" @click="articleDetail(item.id)">
							<view class="flex-item" style="flex-grow: 1;">
								<view class="title font12">
									{{item.title}}
								</view>
								<view style="position: absolute;bottom: 20rpx;display: flex;">
									<!-- <view class="font10 padtop10 padbottom5 font-gray" style="margin-top: 10rpx;">{{item.author}}</view> -->
									<view class="font10 font-gray">
										{{item.view_count}}人看过
									</view>
									<view class="font10 font-gray marginleft15">
										{{item.praise_num}}人点赞
									</view>
								</view>

							</view>
							<view class="right-img flex-item">
								<image :src="item.image"></image>
							</view>

						</view>
					</view>
				</view>
				<!-- 文章		 结束-->



			</view>
			<!-- 性别设置弹窗 -->
			<uni-popup id="genderPopup" ref="genderPopup" type='center' @change="popupChange()">
				<view class="self-dialog" style="background: white;">
					<view class="title text-center">
						<text>请设置用户性别</text>
					</view>
					<view class="content text-center font17">
						不同性别人群尿酸健康范围不同，请设置测试者性别信息
					</view>
					<view>
						 <button class="mini-btn" :class="{ 'btn-select': isActMan }" type="primary" size="mini" @tap="setGender(1)"  >男</button>
						 <button class="mini-btn" :class="{ 'btn-select': isActGirl }" type="primary" size="mini" @tap="setGender(0)" >女</button>

					</view>
					<view>
						<view @tap="comfirn" class="btn  btn-confirm">确定</view>
					</view>
				</view>
			</uni-popup>
			<!-- 连接失败弹窗 -->
			<uni-popup id="connectPopup" ref="connectPopup" type='center' @change="popupChange()">
				<view class="self-dialog" style="background: white;width: 80%;">
					<view class="title text-center" style="color: red;">
						<text>连接失败</text>
					</view>
					<view class="content text-center font17">
						请确认设备是否已启动
					</view>
					<view>
						<view @tap="cancel" class="btn  btn-confirm">确定</view>
					</view>
				</view>
			</uni-popup>
			<!-- 选择设备提示窗 -->
			<uni-popup id="bindChangeDev" ref="bindChangeDev" type='center' @change="popupChange()">
				<view class="self-dialog" style="background: white;width: 90%;">
					<view class="title">
						请选择设备
					</view>
					<view class="flex-start-box box-item" :class="{ 'dev-select': isUa }"   @tap="ChangeDev(4)" style="background:#eef3f8;border-radius: 20rpx;height: 120rpx;">

						<view class="equip-img border-radius4" style="width: 100rpx;height: 100rpx;padding-left: 10rpx;">
							<image src="http://img.aiouning.com/uploader/upload/202110/29/20211029111259617b66bbbbfbd.png" class="publicImg" mode="widthFix"></image>
						</view>
						<view>
							<view class="title padleft5 dev-item">
								<text class="over-ellipsis-two">三诺血糖尿酸仪 UG-11蓝牙</text>

							</view>
						</view>

					</view>
					<view class="flex-start-box box-item"  :class="{ 'dev-select': isGlu }" @tap="ChangeDev(3)" style="background:#eef3f8;margin-top: 20rpx;border-radius: 20rpx;height: 120rpx;" >
						<view class="equip-img border-radius4" style="width: 100rpx;height: 100rpx;padding-left: 10rpx; ">
							<image src="http://img.aiouning.com/uploader/upload/202110/29/20211029111257617b66b93e006.png" class="publicImg" mode="widthFix"></image>
						</view>
						<view>
							<view class="title  padleft5 dev-item" >
								<text class="over-ellipsis-two">三诺血糖仪 安稳+Air</text>

							</view>
						</view>

					</view>
					<view class="flex-start-box box-item"  style="margin-top: 64rpx;">
						<view style="width: 50%;">
							<button class="mini-btn"  type="primary" style="background-color:#979797;color:#fff;border: 0rpx;width: 200rpx;" @click="connel()" >取消</button>
						</view>
						 <view style="width: 50%;">
							 <button class="mini-btn"  type="primary"  style="background-color:#3894ff;color:#fff;border: 0rpx;width: 200rpx;" @click="commit()" >确认</button>

						 </view>

					</view>


				</view>

			</uni-popup>

		</view>

	</view>

</template>

<script>
	import Vue from 'vue'
	import {
		fail
	} from 'assert';
	import store from '@/store/index.js';
	import uniPopup from '@/components/uni-popup/uni-popup.vue'
	import uniPopupDialog from '@/components/uni-popup/uni-popup-dialog.vue'
	// 骨架屏
	import tuiSkeleton from "@/components/tui-skeleton/tui-skeleton"
	import tuiTag from '@/components/tag/tag'
	import F2 from '@/js_sdk/uni-f2/f2.min.js'
	//蓝牙
	import sdkAction from "mcbluetoothsdk";
	import utils from "../../../../utils/sannuo.js";
	import {oss_host} from '@/config/config.js';
	var app = getApp();

	function wrapEvent(e) {
	  if (!e) return
	  if (!e.preventDefault) {
	    e.preventDefault = function() {}
	  }
	  return e
	}
	let chart = null
	const lineCharts = {},
		optionAs = {};
	import {
		mapGetters
	} from 'vuex';
	export default {
		components: {
			tuiSkeleton,
			tuiTag,
			// LineChart,
			uniPopup,
			uniPopupDialog
		},

		data() {
			return {
				echartsData:[],
				mBottom: '0px',
				OSS_HOST: oss_host,
				data: {
					article: [],
					userInfo: {
						bindStatus: false,
						deviceId: ''
					},

					check: {
						status:1
					},
					desc:'',
					bindDev: {
						mac:'',
					},
					bindDevUa: {

					},
					bindDevGlu: {

					}

				},
				devList:[],//链接设备信息
				device_uuid:'',//ios mac地址
				out_time:0,//连接中的时间
				outClient:null,
				changeDevstatus:false,//是否已选择设备
				showEchart: false,
				showMaskloading: false,
				isGlu:false,
				isUa:false,
				timeObj: '',
				connStatus: -1, //蓝牙连接状态  0 未连接  1 连接中  2 已连接
				isCancel: false,
				isBindDev:false, //设备是否绑定
				isActGirl:false,
				isActMan:false,
				gender:1 ,//性别
				product_type:0,
				echartHeight:0,
				echartWidth:0,
				canvasImg:null,
				f2_canvas:{},
				bindDevCount:0,

			};
		},
		created() {

		},
		computed: {
			//获取可使用窗口高度
			windowHeight() {

				return uni.getSystemInfoSync().windowHeight + 'px'
			},
			cWidth() {
				return uni.upx2px(this.width);
			},
			cHeight() {
				return uni.upx2px(this.height);
			},
			...mapGetters(['myDataGlobal', 'netWorkType'])
		},
		watch: {

		},


		/**
		 * 生命周期函数--监听页面加载
		 */
		onLoad: function(e) {
			this.product_type = e.product_type
			uni.setNavigationBarTitle({
				title:this.product_type==3?'血糖管理':'尿酸管理'
			})
			console.log('-----------TYPE',this.product_type)
			// utils.intiFindIndex();
			// console.log(app.globalData.appId)
			// console.log(app.globalData.wxSdkKey)
			//#ifdef MP-WEIXIN
			let _globalData = getApp()
			let _module = uni
			//#endif

			//#ifdef APP-PLUS
			let _globalData = getApp().globalData
			let _module = wx
			//#endif
			sdkAction.initObjDefault(_globalData, _module, {
				'_appId': app.globalData.appId,
				'_wxSdkKey': app.globalData.wxSdkKey
			},function(res) {
							console.log(333, res)
							if(res){
								app.globalData.sdkAccessToken = res.data.sdkAccessToken
							}

									})


		},
		/**
		 * 生命周期函数--监听页面卸载
		 */
		onUnload: function() {
			let _this= this
			console.log('销毁页面')
			uni.closeBluetoothAdapter({
				success(res) {
					console.log('断开设备连接：')
					console.log(res)
				}
			})

			_this.unbindDevice()

		},

			// this.openBluetoothAdapter()

		// onLoad(e){


		// },
		mounted() {

		},
		onShow: function(e) {
			let _this = this;
			
			if (uni.getSystemInfoSync().platform == 'ios') {
				_this.mBottom = '-34px';
			}

			_this.connStatus = 0;//未连接
			_this.getData();

			sdkAction.dispatchConnectState(function(res) {

				console.log('当前设备状态1111', res)
				// _this.connStatus = 2;
				_this.devList =res
				if(res){
					if(res[0].connected){
						_this.connStatus = 2;
					}else{

						_this.outClient=setInterval(function(){

							let s = _this.out_time+1
							_this.changClient(s);
						},1000)
						_this.connStatus = 1;
						// _this.$refs.connectPopup.open()
					}
				}





			})

			console.log('当前设备状态2:',this.connStatus)
		},

		methods: {
			initChart() {
				let _this = this;
				const query = uni.createSelectorQuery().in(this);
				query.select('.f2-canvas')
				  .fields({
				    node: true,
				    size: true
				  })
				  .exec(res => {
				    const { node, width, height } = res[0];
				    const context = node.getContext('2d');
				    const pixelRatio = wx.getSystemInfoSync().pixelRatio;

					this.f2_canvas = node;

				    // 高清设置
				    node.width = width * pixelRatio;
				    node.height = height * pixelRatio;

					_this.echartWidth = width
					_this.echartHeight = height

				    const config = { context, width, height, pixelRatio };

					// // 实例化chart
					const chart = new F2.Chart(config)
					chart.legend(false)

					// Tooltip 配置
					chart.tooltip({
					  showTitle: true, // 展示  tooltip 的标题
					  layout: 'vertical'
					});

					//数据源
					let ticks = []

					chart.source(this.echartsData);
					if(this.product_type==3){
						ticks = [ 0, 3, 6, 9 ];
					}else{
						ticks = [ 0, 130, 260, 390, 520 ]
					}
					 chart.scale('value', {
						min: 0,
						ticks: ticks
					 });
					chart.line().position('date*value').color('type');
					chart.render();

				    if (chart) {
				      this.chart = chart;
				      this.canvasEl = chart.get('el');
				    }
				  });
			},

			getData() {
				let _this = this
				var opt = {
					url: '/blutdruck_check/index',
					data: {
						product_type: this.product_type,
						factory:'sinocare'
					},
					success: function(res) {

						if (res.status) {
							_this.data.article = res.data.article
							_this.data.userInfo = res.data.userInfo
							_this.data.check = res.data.check
							_this.echartsData = res.data.echarts.value
							_this.data.desc = res.data.desc
							_this.gender = res.data.user_member.sex

							_this.data.bindDevGlu=res.data.bindDev
							_this.data.bindDevUa=res.data.bindDevUa
							if(_this.product_type == 4){
								_this.data.bindDev=_this.data.bindDevUa
							}

							if(_this.data.bindDevUa.mac!=undefined && _this.data.bindDevGlu.mac!=undefined){

								_this.changeDevstatus = false
							}else{

								if(_this.data.bindDevUa.mac!=undefined){
									_this.data.bindDev = _this.data.bindDevUa
									_this.changeDevstatus = true
								}else if(_this.data.bindDevGlu.mac!=undefined){
									_this.data.bindDev = _this.data.bindDevGlu
									_this.changeDevstatus = true
								}else{
									_this.changeDevstatus = false
								}
							}
							console.log(_this.changeDevstatus)

							_this.isBindDev = res.data.isBindDev
							// _this.deviceId =_this.data.bindDev.mac
							console.log(_this.isBindDev)


							if (res.data.echarts) {

								setTimeout(function(){
									_this.initChart();
								},1000)
							}


						}

					}
				};
				_this.$service.GetApi(opt)
			},
			changClient(s){
				let _this=this
				if(_this.connStatus == 1){
					// console.log(s)
					if(s>=60){
						_this.$refs.connectPopup.open()
						if(_this.outClient) {
						        clearInterval(_this.outClient);
						        _this.outClient = null;
						}
						_this.out_time = 0
					}else{
						_this.out_time = s
					}
				}else{
					if(_this.outClient) {
					        clearInterval(_this.outClient);
					        _this.outClient = null;
					}
					_this.out_time = 0
				}

			},


			insertData(deviceId, glu=0, unitType,ua=0) {
				let _this = this
				let type=3;
				 if(ua>0){
					type=4;
				}
				var opt = {
					url: '/blutdruck_check/checkInsert',
					data: {
						dev_type: type,//不在是设备类型  测量类型 血糖/尿酸
						mac: deviceId,
						glu: glu,
						ua:ua,
						unit_type: 0,
						// type:type

					},
					success: function(res) {
						//console.log(res)
						if (res.status) {
							_this.showEchart = true;
							// _this.$refs['conn'].close()
							// _this.connStatus =-1;
							//刷新数据
							_this.getData();
						} else {

							// this.connStatus = 22
						}

					}
				};
				_this.$service.GetApi(opt)
			},
			ChangeDev(type){
				let _this = this
				_this.changeDevValue = type
				if(type==4){
					this.isGlu = false;
					this.isUa = true;
				}else{
					this.isGlu = true;
					this.isUa = false;
				}
				// if(type == 4){
				// 	_this.data.bindDev = _this.data.bindDevUa
				// }else{
				// 	_this.data.bindDev = _this.data.bindDevGlu
				// }
				// _this.changeDevstatus = true
				// _this.$refs.bindChangeDev.close()
				// _this.link()
			},
			connel(){
				this.$refs.bindChangeDev.close()
			},
			commit(){
				let _this= this
				if(!_this.changeDevValue){

					return
				}
				if(_this.changeDevValue == 4){
					_this.data.bindDev = _this.data.bindDevUa
				}else{
					_this.data.bindDev = _this.data.bindDevGlu
				}
				_this.changeDevstatus = true
				_this.$refs.bindChangeDev.close()
				_this.link()
			},
			//获取mac地址 没有跳转到
			link(){
				//
				let _this = this
				if(_this.product_type==3 && _this.changeDevstatus == false){
					//弹框  有两个设备以上
					if(_this.data.bindDevUa && _this.data.bindDevGlu){
						_this.$refs.bindChangeDev.open()
						return
					}else{
						if(_this.data.bindDevUa){
							_this.data.bindDev = _this.data.bindDevUa
						}else{
							_this.data.bindDev = _this.data.bindDevGlu
						}
					}
				}
				console.log(_this.data.bindDev);
				if(_this.data.bindDev.dev_type == 3){
					_this.currentDeviceType = 25 //血糖
				}else if(_this.data.bindDev.dev_type == 4)
				{
					_this.currentDeviceType = 26 //血糖尿酸
				}

				// this.currentDeviceType = this.data.bindDev.dev_type
				//A458E489-F207-4EAA-4E4C-7E11AE06D0E9  ios-mac
				let deviceUUId = _this.data.bindDev.mac
				app.globalData.bindDeviceList = [{
					deviceType: _this.currentDeviceType,
					deviceUUId: deviceUUId,
					deviceName: deviceUUId
				}];


				_this.connStatus = 1;//
				_this.outClient=setInterval(function(){

					let s = _this.out_time+1
					_this.changClient(s);
				},1000)
				_this.openBluetoothAdapter()
				if (uni.setKeepScreenOn) {
					uni.setKeepScreenOn({
						keepScreenOn: true,
						success: function(res) {
							console.log('正保持屏幕常亮');
						}
					});
				}



			},
			// 初始化蓝牙模块
			openBluetoothAdapter: function() {
				let that = this;
				that.device_uuid  = that.data.bindDev.mac

				uni.openBluetoothAdapter({
					mode:'central',
					success: function(res) {
						uni.showToast({
							title: '打开蓝牙适配器成功！',
							icon: 'none',
							duration: 1500
						});
						if(uni.getSystemInfoSync().platform=='ios' && !that.data.bindDev.device_uuid  ){
							console.log('ios系统1 ')
							let mac = that.data.bindDev.mac
							uni.startBluetoothDevicesDiscovery({
							  services: [],
							  success (res) {
								  that.onBluetoothDeviceFound()
							    console.log('su******-------',res)
							  },
							  fail(res){
								  console.log('error******-------',res)
							  }
							})
						}else if(uni.getSystemInfoSync().platform=='ios' && that.data.bindDev.device_uuid){
							console.log('ios系统2 ')
							console.log(that.data.bindDev.device_uuid)
							app.globalData.bindDeviceList[0].deviceUUId = that.data.bindDev.device_uuid
							that.device_uuid = that.data.bindDev.device_uuid
							that.bindDev()
						}else{
							that.bindDev()
						}


						console.log(app.globalData.bindDeviceList)
						//bindDeviceList 链接设备的信息

						console.log('打开蓝牙适配器成功')
						var log = that.textLog + "打开蓝牙适配器成功！\n";
						that.isBlueToothOpen = true
						// that.setData({
						// 	textLog: log,
						// 	isBlueToothOpen: true
						// });
					},
					fail: function(err) {
						that.connStatus = 0;
						var log = that.textLog + "蓝牙开关未开启 \n";
						that.isBlueToothOpen = false


						uni.showModal({
							title: '提示',
							content: "蓝牙开关未开启",
							showCancel: false
						});
					}
				}); // 监听蓝牙适配器状态变化事件

				uni.onBluetoothAdapterStateChange(function(res) {
					console.log(33333)
					console.log(res)

				});
			},
			// 监听寻找到新设备的事件
			onBluetoothDeviceFound: function() {
				var that = this;
				uni.onBluetoothDeviceFound(function(res) {
					res.devices.forEach(function(device) {
						console.log('222222',device)
			// 			if (!device.name && !device.localName) {
			// 				return;
			// 			}

						var macAddrStr = utils.ab2hex(device.advertisData).toUpperCase().replace(
							/(.{2})/g, '$1:');
						console.log(macAddrStr)
						device.macAddr = macAddrStr.substring(macAddrStr.length - 18, macAddrStr
							.length - 1);
						console.log(device.macAddr)
						if(that.data.bindDev.mac ==device.macAddr ){
							app.globalData.bindDeviceList[0].deviceUUId = device.deviceId;
							that.device_uuid = device.deviceId
							console.log('ios:',app.globalData.bindDeviceList[0].deviceUUId)
							//停止蓝牙搜索
							that.stopBluetoothDevicesDiscovery();
						}
			// 			const foundDevices = that.devices;
			// 			const idx = utils.inArray(foundDevices, 'deviceId', device.deviceId);
			// 			const data = {};

			// 			if (idx === -1) {
			// 				data[`devices[${foundDevices.length}]`] = device;
			// 			} else {
			// 				data[`devices[${idx}]`] = device;
			// 			}

			// 			that.setData(data);
					});
				});
			},
			stopBluetoothDevicesDiscovery: function() {
				var that = this;
				var log = that.textLog + "停止搜寻附近的蓝牙外围设备 \n";
				console.log(log)
				uni.stopBluetoothDevicesDiscovery();
				that.bindDev()
				that.setMacIos()
			},
			closeConnection: function() {
				console.log('****',this.device_uuid)//调用失败 stopConnectDevice找不到此方法
				sdkAction.stopConnectDevice(this.device_uuid, function() {
					console.log(12112121)
					// uni.navigateTo({
					// 	url: '/pages/selectDevice/startpage'
					// });
				}, true);
			},
			unbindDevice: function() {
				var that = this;
				sdkAction.closeBlueTooth(function(res) {
					 
					console.log('t', res)
					var appBindDeviceList = app.globalData.bindDeviceList;

					if (appBindDeviceList.length) {
						if (appBindDeviceList.length === 1) {
							app.globalData.bindDeviceList = [];
						} else {
							var deleteIdx = -1;

							for (let i = 0; i < appBindDeviceList.length; i++) {
								if (appBindDeviceList[i].deviceUUId === that.deviceId) {
									deleteIdx = i;
								}
							}

							app.globalData.bindDeviceList.splice(deleteIdx, 1);
						}
					}
					console.log('bindDeviceList', app.globalData.bindDeviceList)


				});
			},
			bindDev(){
				let that = this
				let bindDeviceList = app.globalData.bindDeviceList;

				bindDeviceList.map((v) => {
					console.log(1)
					console.log(v.deviceUUId)
					//初始化链接            mac          回调
					sdkAction.doInitMulti(v.deviceUUId, function() {
						console.log('2222222')
						console.log('初始化链接成功')

						//链接设备  设备类型 （唯一）  mac地址   回调
						sdkAction.startMultiConnectDevice(v.deviceType, v.deviceUUId,
							function(res) {
								console.log('链接设备成功:返回测量结果')
								//测量结果从这返回
								console.log(22, res)
								// var log = that.textLog + JSON.stringify(
								// 	res) + "\n";
								// that.textLog = log
								if(res.durDeviceInfo){
									let devInfo = res.durDeviceInfo
									let GLU =0
									let UA = 0
									switch(devInfo.deviceType){
										case  25:
											//血糖
											 GLU = res.GLU

											that.insertData(that.data.bindDev.mac,GLU,that.data.bindDev.dev_type,0)

											break
										case  26:
											//血糖
											 GLU = res.GLU
											 UA = res.UA
											that.insertData(that.data.bindDev.mac,GLU,that.data.bindDev.dev_type,UA)

											break
										default:

										    break;
									}
								}

							})
					})
				})
			},
			setMacIos(){
				let _this = this
				var opt = {
					url: '/SinocareDev/setDeviceUuid',
					data: {
						device_uuid:_this.device_uuid,
						dev_type:_this.data.bindDev.dev_type
					},
					success: function(res) {
						console.log(res)


					}
				};
				_this.$service.GetApi(opt)
			},



			 //解决画布数据图层级太高挡住弹出窗问题

			 handleCanvarToImg() {
			    var _this=this;
				//当有弹出窗的时候讲画布转成图片替换掉画布即可
			    uni.canvasToTempFilePath({
			      canvas: _this.f2_canvas,
			      success: function(res) {
					  _this.canvasImg = res.tempFilePath
			      }
			    });
			  },
			touchStart(e) {
			  const canvasEl = this.canvasEl
			  if (!canvasEl) {
				return
			  }
			  canvasEl.dispatchEvent('touchstart', wrapEvent(e))
			},
			touchMove(e) {
			  const canvasEl = this.canvasEl
			  if (!canvasEl) {
				return
			  }
			  canvasEl.dispatchEvent('touchmove', wrapEvent(e))
			},
			touchEnd(e) {
			  const canvasEl = this.canvasEl
			  if (!canvasEl) {
				return
			  }
			  canvasEl.dispatchEvent('touchend', wrapEvent(e))
			},
			//测量结果说明
			testResult() {
				let _this = this
				this.$refer.setVilit('test_result')
				let callback = function(url) {
					_this.$refs.popupvLogin.open()
				}
				var data = {
					product_type:this.product_type
				}

				this.$refer.toUrl(callback, data)
				return
			},
			//更多数据
			testRecord() {
				let _this = this
				this.$refer.setVilit('/packageHealthy/pages/test_record/test_record')
				let callback = function(url) {
					_this.$refs.popupvLogin.open()
				}
				var data = {
					group_id: 0,
					product_type: this.product_type
				}
				this.$refer.toUrl(callback, data)
				return
			},
			articleDetail(id) {
				let _this = this
				uni.closeBluetoothAdapter({
					success(res) {
						console.log('断开设备连接：')
						console.log(res)
					}
				})

				_this.unbindDevice()
				this.$refer.setVilit('/packageArticle/pages/healthy-article/article_detail')
				let callback = function(url) {
					_this.$refs.popupvLogin.open()
				}
				var data = {
					id: id
				}
				this.$refer.toUrl(callback, data)
				return
			},
			// 文章推荐
			pageArticleList() {
				let _this = this
				this.$refer.setVilit('/packageArticle/pages/healthy-article/article_list')
				let callback = function(url) {
					_this.$refs.popupvLogin.open()
				}
				var data = {
					product_type:this.product_type
				}
				this.$refer.toUrl(callback, data)
				return
			} ,
			genderPopup(){

				this.$refs.genderPopup.open();
			},
			//性别设置保存
			comfirn(){
				if(!this.isActMan && !this.isActGirl){
					uni.showToast({
						title:'请选择性别',
						icon:'none'
					})

					return ;
				}
				this.$refs.genderPopup.close();

				let _this = this
				var opt = {
					url: '/sinocare_dev/setGender',
					data: {
						value:this.isActMan?1:0
					},
					success: function(res) {
						//console.log(res)
						if (res.status==1) {
							 _this.gender = _this.isActMan==true?1:0;
						}
					}
				};
				_this.$service.GetApi(opt)
			},
			setGender(value){
				if(value==1){
					this.isActGirl = false;
					this.isActMan = true;
				}else{
					this.isActGirl = true;
					this.isActMan = false;
				}

			},
			cancel(){
				this.$refs.connectPopup.close();
			},
			//根据弹出层显示状态来切换画布和图片的显示
			popupChange(e){
				if(!e.show){
					this.canvasImg = null;
				}else{
					this.handleCanvarToImg();
				}

			},
			toBindDev(){

				let _this = this
				this.$refer.setVilit('packageHealthy/pages/bind_equip/scan_code_bind')
				let callback = function(url) {
					_this.$refs.popupvLogin.open()
				}

				this.$refer.toUrl(callback)
				return
			}

		},
	};
</script>

<style lang="scss">
	@import "./index.scss";
</style>
